package com.cxy.ch1.syn;

import com.cxy.tools.SleepTools;

/**
 * 
 * @ClassName: StaticAndClass
 * @Description: TODO(类锁和锁static变量也是不同的)
 * @author 菜徐鸭
 * @date 2020年4月12日
 *
 */
public class StaticAndClass {

	private static class SynClass extends Thread {
		@Override
		public void run() {
			System.out.println(currentThread().getName() + ":SynClass is running...");
			synClass();
		}
	}

	private static class SynStatic extends Thread {
		@Override
		public void run() {
			System.out.println(currentThread().getName() + "SynStatic is running...");
			synStatic();
		}
	}

	private static synchronized void synClass() {
		System.out.println(Thread.currentThread().getName() + "synClass going...");
		SleepTools.second(1);
		System.out.println(Thread.currentThread().getName() + "synClass end");
	}

	private static Object obj = new Object();

	private static void synStatic() {
		synchronized (obj) {
			System.out.println(Thread.currentThread().getName() + "synStatic going...");
			SleepTools.second(1);
			System.out.println(Thread.currentThread().getName() + "synStatic end");
		}
	}

	/**
	 * 每一个类在类加载都会有一个class对象，static加锁意味加锁的是class对象 类锁和对象锁是互不干扰的
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		StaticAndClass synClassAndInstance = new StaticAndClass();
		Thread t1 = new SynClass();
		// Thread t2 = new SynStatic();
		Thread t2 = new SynClass();
		t2.start();
		SleepTools.second(1);
		t1.start();
	}
}
